/* Copyright 2011 Elektrobit Wireless Communications Oy (EB)


  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 2 as 
  published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


 *All rights reserved 
 *Version:Elektrobit_Qt_1.0.0_20110305 */


#include "piccovert.h"
#include "appcommon.h"
#include <QDesktopServices>
#include <QImage>
#include <QMutexLocker>
#include <QDir>


PicCovert::PicCovert(int w, int h, const QStringList &srcPathList, const QString& destPath, QObject *parent) : QThread(parent) {
    this->w = w;
    this->h = h;
    this->srcPathList = srcPathList;
    this->destPath = destPath;
    this->list.clear();
    this->start();
}

void PicCovert::run( void ) {


    QDir picDestDir(destPath);
    if( !picDestDir.exists() ) {
        picDestDir.mkpath(destPath);
    }

    if(destPath.at(destPath.count() - 1)  != '/')
    {
        destPath.append('/');
    }

    for (int i = 0; i < srcPathList.count(); i++)
    {
        QDir picSrcDir(srcPathList.at(i));

        QStringList picFilter = QString("*.png;*.jpg;*.jpeg;*.bmp;*.gif").split(";");
        QFileInfoList picInfoList = picSrcDir.entryInfoList(picFilter);

        QString oldFilePath = "";
        QString newFilePath = "";
        APPINFO << picInfoList.count();
        foreach(QFileInfo fileInfo,picInfoList) {
    //        APPINFO << fileInfo.absoluteFilePath();
            oldFilePath = fileInfo.absoluteFilePath();
            newFilePath = destPath + fileInfo.baseName() + QString("_%1x%2").arg(this->w).arg(this->h) + ".png";
            QDir dir(newFilePath);
            convert(oldFilePath,dir.absolutePath());
        }
    }

}

bool PicCovert::convert(const QString & oldFilePath, const QString &newFilePath) {
    if(QFile::exists(oldFilePath) == false) {
        return false;
    }

    if(QFile::exists(newFilePath) == true) {
        QMutexLocker locker(&mutex);
        list.append(newFilePath);
        return true;
    }

    QImage image;
    if ( !image.load(oldFilePath) ) {
            return false;
    }
    if ((this->w != image.width()) || (this->h != image.height())) {
            image = image.scaled(w, h, Qt::IgnoreAspectRatio,  Qt::SmoothTransformation);
    }
    image.save(newFilePath, "png");

    QMutexLocker locker(&mutex);

    list.append(newFilePath);

    return true;
}


QStringList * PicCovert::getList(void) {
    QMutexLocker locker(&mutex);
    return &list;
}


















